package com.ws.lv.interceptor;
import com.ws.lv.bean.Acl_user;
import com.ws.lv.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Set;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在被访问的资源前执行
        String requestURI = request.getRequestURI().substring(request.getContextPath().length());
        System.out.println("preHandle 拦截器————————————————————————————————————————"+requestURI);
        // 获取用户
        Acl_user aclUser = (Acl_user) request.getSession().getAttribute("aclUser");
        // 获取权限
        Set<String> permissions = (Set<String>) request.getSession().getAttribute("permissions");
        if (aclUser!=null){
            if(permissions.contains(requestURI)){
                return true;
            }else{
                response.sendRedirect(request.getContextPath()+"/noperm.jsp");
                return false;
            }
        }else {
            PrintWriter writer = response.getWriter();
            writer.write("<script>window.parent.location.href='"+request.getContextPath()+"/acl_user/outLogin'</script>");
            writer.close();
            return false;
        }



    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("控制器方法后  渲染视图前 postHandle 拦截器。。。。。。。。。。。。");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("最后  afterCompletion。。。。。。。。。。。。");
    }
}

